<?php

namespace app\controller\system;

use app\controller\BaseController;
use app\model\system\SysUser;
use app\service\JwtService;
use Firebase\JWT\JWT;
use support\Request;
use support\Response;
use support\Log;
use Mickeywaugh\Captcha\CaptchaBuilder;
use support\Redis;

class AuthController extends BaseController
{
    public $noNeedLogin = ["login", "captcha"];
    public function captcha(): Response
    {
        try {
            // 生成随机验证码文本
            $captchaBuilder = new CaptchaBuilder();
            $captchaBuilder->setBackgroundColor(0, 0, 0, 127)->build();
            $captchaCode = $captchaBuilder->getPhrase();
            // 生成验证码图片
            $captchaImage = $captchaBuilder->inline();
            // 生成唯一标识符
            $captchaId = md5(uniqid() . microtime());
            // 将验证码存储到Redis中，设置过期时间
            Redis::setex("captcha:" . $captchaId, 300, $captchaCode); // 5分钟过期
            // 返回验证码ID和图片base64编码
            return $this->success([
                'captchaKey' => $captchaId,
                'captchaBase64' => $captchaImage
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return $this->error($e->getMessage());
        }
    }

    public function login(Request $request): Response
    {
        $postData = $request->post(); //username,password,captchaId,captchaCode
        extract($postData);

        if (!isset($username) || !$username) return $this->error("用户名为空");
        if (!isset($password) || !$password) return $this->error("密码为空");

        if (isset($captchaId)  && isset($captchaCode)) {
            // 验证码验证
            if (!$captchaId) return $this->error("验证码ID为空");
            if (!$captchaCode) return $this->error("验证码为空");
            $redisCaptcha = Redis::get("captcha:" . $captchaId);
            if ($redisCaptcha == null) {
                return $this->error("验证码已过期" . $captchaId);
            } else {
                if ($redisCaptcha != $captchaCode) {
                    return $this->error("验证码错误");
                } else {
                    Redis::del("captcha:" . $captchaId);
                }
            }
        }

        // 用户验证
        $user = SysUser::where('username', $username)->where("status", 1)->where("is_deleted", 0)->find();
        if (!$user) {
            return $this->error("用户名不存在");
        }

        if (!password_verify($password, $user->password)) {
            return $this->error("密码错误");
        }

        try {
            $payload = [
                'userName' => $user->username,
                'userId' => $user->id,
                'expire' => time() + 3600 * 24 * 7,
            ];
            //生成redis key
            $payload["md5"] = md5($user->username . $user->password);
            $token = JWT::encode($payload, $_ENV['JWT_SECRET'], 'HS256');

            if (JWTService::saveToken($payload["md5"], $token)) {
                return $this->success([
                    'tokenType' => 'Bearer',
                    'accessToken' => $token,
                    'refreshToken' => '',
                    'expiresIn' => ''
                ]);
            } else {
                return $this->error("Save token failed");
            };
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return $this->error($e->getMessage());
        }
    }

    public function wexinLogin(Request $request): Response
    {
        $code = $request->post('code');
        try {
            // $res = (new WeChatService())->getUserInfo($code);
            $token = "";
            return $this->success([
                'tokenType' => 'Bearer',
                'accessToken' => $token,
                'refreshToken' => '',
                'expiresIn' => ''
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return $this->error($e->getMessage());
        }
    }

    public function wxMiniapp(Request $request): Response
    {
        try {
            $data = $request->post(); //code,encryptedData,iv
            extract($data);
            // $wx = new WxMiniapp();
            // $userInfo = $wx->getUserInfo($code, $encryptedData, $iv);
            $token = "";
            return $this->success([
                'tokenType' => 'Bearer',
                'accessToken' => $token,
                'refreshToken' => '',
                'expiresIn' => ''
            ]);
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return $this->error($e->getMessage());
        }
    }

    public function logout(Request $request): Response
    {
        $jwt = $request->header('Authorization');
        $jwtDecode = JwtService::decodeToken($jwt);
        if (Redis::del($jwtDecode->redisKey)) {
            return $this->success(["token" => $jwt]);
        } else {
            return $this->error("remove token failed");
        };
    }

    public function sendSms(Request $request): Response
    {
        $phone = $request->post('mobile');
        if (!$phone) {
            return $this->error("手机号不能为空");
        }
        $code = rand(1000, 9999);
        Redis::setex("sms:{$phone}", 60, $code);
        return $this->success(["code" => $code]);
    }
}
